package com.cgwx.service.impl;

import com.cgwx.config.BusinessException;
import com.cgwx.entity.Folder;
import com.cgwx.entity.FsTransmitRecord;
import com.cgwx.entity.UsUser;
import com.cgwx.mapper.FolderMapper;
import com.cgwx.mapper.FsTransmitRecordMapper;
import com.cgwx.mapper.UserMapper;
import com.cgwx.service.IFolderService;
import com.cgwx.service.IFsTransmitRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class FsTransmitRecordServiceImpl implements IFsTransmitRecordService {

    @Resource
    private FsTransmitRecordMapper fsTransmitRecordMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private FolderMapper folderMapper;
    @Resource
    private IFolderService folderService;
    private final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-SSS");

    @Override
    public List<FsTransmitRecord> getFsTransmitRecord(FsTransmitRecord fsTransmitRecord) {
        return fsTransmitRecordMapper.getFsTransmitRecord(fsTransmitRecord);
    }

    @Override
    public List<FsTransmitRecord> getFsTransmitRecord(FsTransmitRecord fsTransmitRecord, String column, String sort) {
        fsTransmitRecord.setColumn(column);
        fsTransmitRecord.setSort(sort);
        return fsTransmitRecordMapper.getFsTransmitRecord(fsTransmitRecord);
    }

    @Override
    @Transactional
    public boolean updateFsTransmitRecord(String savePath, Map<String, String> map, LocalDateTime time) {
        FsTransmitRecord fsTransmitRecord = new FsTransmitRecord();
        fsTransmitRecord.setSavePath(savePath);
        List<FsTransmitRecord> fsTransmitRecordList = getFsTransmitRecord(fsTransmitRecord);
        if(fsTransmitRecordList == null || fsTransmitRecordList.isEmpty()){
            log.warn("updateTransmitTask文件传输记录不存在!{}", savePath);
            throw new BusinessException("文件传输记录不存在!" + savePath);
        } else if (fsTransmitRecordList.size() > 1) {
            log.warn("updateTransmitTask文件传输记录不唯一!{}", savePath);
            throw new BusinessException("文件传输记录不唯一!" + savePath);
        }
        fsTransmitRecord = fsTransmitRecordList.get(0);

        fsTransmitRecord.setCompleteTime(time);
        fsTransmitRecord.setStatus("传输完成");
        int totalNum = Integer.parseInt(fsTransmitRecord.getTotalNum());
        fsTransmitRecord.setFailNum(String.valueOf(totalNum - map.size()));
        fsTransmitRecord.setSuccessNum(String.valueOf(map.size()));
        if(!fsTransmitRecordMapper.updateFsTransmitRecord(fsTransmitRecord)){
            log.warn("updateTransmitTask文件传输记录修改失败!{}", savePath);
            throw new BusinessException("updateTransmitTask文件传输记录修改失败!" + savePath);
        }
        return true;
    }

    @Override
    public boolean insertFsTransmitRecord(String account, String totalNum, String savePath) {
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userMapper.getUser(user).get(0);
        FsTransmitRecord fsTransmitRecord = new FsTransmitRecord();
        fsTransmitRecord.setId(generateId());
        fsTransmitRecord.setStatus("传输中");
        fsTransmitRecord.setTaskName(LocalDateTime.now().format(formatter) + "_" + user.getName());
        fsTransmitRecord.setPath("个人空间/外部传输文件夹/" + LocalDate.now().format(monthFormatter));
        Folder folder = getSaveFolder(account);
        if(folder == null) {
            log.warn("insertFsTransmitRecord文件传输文件夹查找失败!{}", account);
            throw new BusinessException("insertFsTransmitRecord文件传输文件夹查找失败!" + account);
        }
        fsTransmitRecord.setParentId(folder.getEntityId());
        fsTransmitRecord.setOwnerAccount(account);
        fsTransmitRecord.setOwnerName(user.getName());
        fsTransmitRecord.setSavePath(savePath);
        fsTransmitRecord.setTotalNum(totalNum);
        System.out.println("insertFsTransmitRecord: " + fsTransmitRecord);
        return fsTransmitRecordMapper.insertFsTransmitRecord(fsTransmitRecord);
    }

    public String generateId() {
        return UUID.randomUUID().toString();
    }

    public Folder getSaveFolder(String account) {
        Folder folderTrans = new Folder();
        folderTrans.setOwnerAccount(account);
        folderTrans.setEntityName("外部传输文件夹");
        List<Folder> folders = folderMapper.getFolder(folderTrans);
        if(folders == null || folders.isEmpty()) {
            log.warn("getSaveFolder文件传输文件夹查找失败!{}", account);
            throw new BusinessException("getSaveFolder文件传输文件夹查找失败!" + account);
        }
        Folder folder = null;
        if(folders.size() > 1){
            for(Folder folderTrans0 : folders) {
                folder = new Folder();
                folder.setEntityId(folderTrans0.getParentId());
                List<Folder> folderTrans0s = folderMapper.getFolder(folderTrans);
                if(folderTrans0s == null || folderTrans0s.isEmpty()) {
                    log.warn("我的文件夹查找失败!{}", account);
                    throw new BusinessException("我的文件夹查找失败!" + account);
                }
                if(folderTrans0s.get(0).getEntityName().equals("我的文件夹")){
                    folder = folderTrans0s.get(0);
                    break;
                }
            }
        }
        else folder = folders.get(0);
        if(folder == null) return null;
        else{
            Folder result = new Folder();
            result.setParentId(folder.getEntityId());
            String month = LocalDate.now().format(monthFormatter);
            result.setEntityName(month);
            List<Folder> newFolders = folderMapper.getFolder(result);
            if(newFolders == null || newFolders.isEmpty()) {
                //新建文件夹
                Timestamp time = Timestamp.valueOf(LocalDateTime.now());
                result.setCreateTime(time);
                result.setEntityRoom(folder.getEntityRoom());
                result.setType("folder");
                result.setIsOuter("1");
                result.setOwnerAccount(account);
                result.setOwnerName(folder.getOwnerName());
                result.setEntityId(folderService.generateEntityId());
                log.info("insertFolder: {}", result);
                boolean insertRes = folderMapper.insertFolder(result);
                if(!insertRes) {
                    log.warn("getSaveFolder新增文件夹失败!{}", account);
                    throw new BusinessException("getSaveFolder新增文件夹失败!" + account);
                }
                result.setParentId(folder.getEntityId());
                result.setEntityName(month);
                newFolders = folderMapper.getFolder(result);
                newFolders.add(folder);
            }
            return newFolders.get(0);
        }
    }
}
